﻿using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Forms;
using JetBrains.Annotations;
using SG.Sys.Console.Cntrl;
using SG.Sys.Console.Process;
using SG.Sys.Console.Tab;

namespace SG.Sys.Console.View
{
    public partial class MainConsole : Form
    {
        private static readonly string DefaultTitle = string.Format("CLI x{0:d}", Environment.Is64BitProcess ? 64 : 32);

#pragma warning disable 0649
        [UsedImplicitly] private Composer _composer;

        [Import(typeof(ITabManager), RequiredCreationPolicy = CreationPolicy.NonShared)]
        private ITabManager _tabManager;
#pragma warning restore 0649

        public MainConsole()
        {
            InitializeComponent();
            _composer = new Composer(this);
        }

        private void MainConsole_Load(object sender, EventArgs e)
        {
            _tabManager.Control = tabs;
            _tabManager.OnTitleChanged += _tabManager_OnTitleChanged;
            _tabManager.AutoLoadTabs();

            FillProcessWrapperFactories();
            
            Activate();
        }

        private void FillProcessWrapperFactories()
        {
            var groups = processWrapperFactoriesView.Groups;
            var autoLoadableGroup = groups["autoLoadableGroup"];
            var normalGroup = groups["normalGroup"];

            var listItemCreator =
                from lazy in Program.Instance.ProcessWrapperFactories
                let meta = lazy.Metadata
                let columData = new[] {meta.Name, meta.Author, meta.Version, meta.Release}
                select new ListViewItem(columData, meta.AutoLoad ? autoLoadableGroup : normalGroup) {Tag = lazy.Value};

            foreach (var item in listItemCreator)
            {
                processWrapperFactoriesView.Items.Add(item);
            }
        }

        void _tabManager_OnTitleChanged(object sender, TitleChangedEventArgs e)
        {
            Text = string.Format("{0} - {1}", DefaultTitle, e.Title);
        }

        private void MainConsole_FormClosing(object sender, FormClosingEventArgs e)
        {
            _tabManager.SendClose();
        }

        private void processWrapperFactoriesView_DoubleClick(object sender, EventArgs e)
        {
            var items = processWrapperFactoriesView.SelectedItems;

            foreach (var factory in from object item in items select (IProcessWrapperFactory) items[0].Tag)
                _tabManager.NewTab(factory.NewProcessWrapper());
        }
    }
}
